package yf.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.yf.response.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.common.Const;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.*;
import yf.mall.service.MyService;
import yf.mall.vo.AccountMyProfitVO;
import yf.mall.vo.MallOrderVo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaolongtongxie
 * @version 1.0
 * @date 2020/6/11 18:17
 */
@Service
@Slf4j
public class MyServiceImpl implements MyService {

    @Autowired
    private MallOrderDao mallOrderDao;
    @Autowired
    private AccountRecordDao accountRecordDao;
    @Autowired
    private ShopDao shopDao;

    /**
     * Long
     * 待付款
     *
     * @param userId
     * @param orderStatus
     * @param payStatus
     * @param limit
     * @param page
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<MallOrderVo> myOrderList(Long userId, Integer orderStatus, Integer payStatus, int page, int limit) {
        PageHelper.startPage(page, limit).setOrderBy("mallOrder.order_time desc");
        List<MallOrderVo> orderVos = this.mallOrderDao.queryByUserIdAndPayStatus(userId, orderStatus, payStatus);
        //组装明细
        for (MallOrderVo orderVo : orderVos) {
            List<OrderItemEntity> itemEntities = orderItemDao.findByOrderId(orderVo.getMallOrder().getId());
            orderVo.getMallOrder().setItems(itemEntities);
            //获取店铺
            ShopEntity shopEntity = shopDao.findByUserId(orderVo.getFromUser().getId());
            if (shopEntity != null) {
                orderVo.setShopEntity(shopEntity);
            }
        }
        return orderVos;
    }

/*
    @Override
    public OrderMyInfo findOrderStatus(Long userId) {
        OrderMyInfo info = new OrderMyInfo();
        Integer wait = this.mallOrderDao.total(userId, MallOrderOrderStatusEnum.NEW.getIndex(), MallOrderPayStatusEnum.NOT_PAID.getIndex());
        if (wait!=null){
            info.setWaitOrderNum(wait);
        }
        Integer delivered = this.mallOrderDao.total(userId, MallOrderOrderStatusEnum.DELIVERED.getIndex(), -1);
        if (delivered!=null) {
            info.setDeliveredOrderNum(delivered);
        }
        return info;
    }*/

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private UserDao userDao;

    /**
     * que
     * 扣进货金额
     */

    public List<String> recursionOrderNo(String orderNo, List<String> res) {
        List<AccountRecordEntity> entities;
        //根据订单编号remark获取订单  针对代理有利产品
        List<MallOrderEntity> mallOrderEntitys = mallOrderDao.findByRemark(orderNo);
        if (mallOrderEntitys != null) {
            for (MallOrderEntity mallOrderEntity : mallOrderEntitys) {
                //根据订单编号查询账户记录
                entities = accountRecordDao.findByInfo(mallOrderEntity.getOrderNo());
                if (entities != null && entities.size() > 0) {
                    //获取订单带来连锁奖励
                    for (AccountRecordEntity orderEntity : entities) {
                        if (null != orderEntity.getInfo() && orderEntity.getInfo().contains(MallOrderBusTypeEnum.AUTO_BUY.getValue())) {
                            // res.add(userDao.get(orderEntity.getFromUserId()).getName() + MallOrderBusTypeEnum.AUTO_BUY.getValue() + itemVo.getGoodsName() + orderEntity.getAmount());
                            res.add(userDao.get(orderEntity.getFromUserId()).getName() + MallOrderBusTypeEnum.AUTO_BUY.getValue() + orderEntity.getAmount());
                        }
                        if (null != orderEntity.getInfo() && orderEntity.getInfo().contains(MallOrderBusTypeEnum.RETURN.getValue())) {
                            res.add(userDao.get(orderEntity.getFromUserId()).getName() + MallOrderBusTypeEnum.RETURN.getValue());
                        }
                    }
                }
            }
        }
        // 不存在返回
        return res;
    }

    /**
     * que
     * 根据订单编号递归查询
     */

//    public List<String> findOrderNo(String orderNo, List<String> res) {
//        List<AccountRecordEntity> entities;
//        if (null != orderNo && !("").equals(orderNo)) {
//            //根据订单编号查询账户记录
//            entities = accountRecordDao.findByInfo(orderNo);
//            if (entities != null && entities.size() > 0) {
//                //获取订单带来连锁奖励
//                String name = "";
//                MallOrderEntity orderEntity = mallOrderDao.findByOrderNo(orderNo);
//                UserEntity userEntity = userDao.get(orderEntity.getUserId());
//                for (AccountRecordEntity accountRecordEntity : entities) {
//                    //分享奖励
//                    if (accountRecordEntity.getBus() == AccountRecordBusEnum.SHARE_REWARD.getIndex()) {
//                        name = "";
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.CASH.getIndex())) {
//                            name = AccountRecordTypeEnum.CASH.getValue();
//                        }
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.COUPON.getIndex())) {
//                            name = AccountRecordTypeEnum.COUPON.getValue();
//                        }
//
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.VOUCHER.getIndex())) {
//                            name = AccountRecordTypeEnum.VOUCHER.getValue();
//                        }
//                        res.add(userEntity.getName() + userEntity.getCode() + "下单,给" + userDao.get(accountRecordEntity.getToUserId()).getName() + AccountRecordBusEnum.SHARE_REWARD.getValue() + name + accountRecordEntity.getAmount() + "," + Const.ORDER_NO + orderEntity.getOrderNo());
//                    }
//                    //经验值
//                    if (accountRecordEntity.getType() == AccountTypeEnum.EXP.getIndex() && accountRecordEntity.getBus().equals(AccountRecordBusEnum.TRANSFER.getIndex())) {
//                        if (accountRecordEntity.getToUserId().equals(Const.ADMIN_ID)) {
//                            res.add(userEntity.getName() + userEntity.getCode() + "下单," + userDao.get(accountRecordEntity.getToUserId()).getName() + "追回" + userDao.get(orderEntity.getUserId()).getName() + AccountTypeEnum.EXP.getValue() + accountRecordEntity.getAmount() + "," + Const.ORDER_NO + orderEntity.getOrderNo());
//                        } else {
//                            MallOrderEntity order = mallOrderDao.findByOrderNo(orderNo);
//                            if (order.getUserId().equals(accountRecordEntity.getToUserId())) {
//                                res.add(userEntity.getName() + userEntity.getCode() + "下单," + userDao.get(accountRecordEntity.getToUserId()).getName() + AccountTypeEnum.EXP.getValue() + "增加" + accountRecordEntity.getAmount() + "," + Const.ORDER_NO + orderEntity.getOrderNo());
//                            } else {
//                                res.add(userDao.get(accountRecordEntity.getToUserId()).getName() + userDao.get(accountRecordEntity.getToUserId()).getCode() + MallOrderBusTypeEnum.AUTO_BUY.getValue() + "," + userDao.get(accountRecordEntity.getToUserId()).getName() + userDao.get(accountRecordEntity.getToUserId()).getCode() + AccountTypeEnum.EXP.getValue() + "增加" + accountRecordEntity.getAmount() + "," + Const.ORDER_NO + orderEntity.getOrderNo());
//                            }
//                        }
//                    }
//                    //区域奖励
//                    if (accountRecordEntity.getBus() == AccountRecordBusEnum.AREA_REWARD.getIndex()) {
//                        res.add(userEntity.getName() + userEntity.getCode() + "下单,给" + userDao.get(accountRecordEntity.getToUserId()).getName() + AccountRecordBusEnum.AREA_REWARD.getValue() + AccountRecordTypeEnum.CASH.getValue() + accountRecordEntity.getAmount() + "," + Const.ORDER_NO + orderEntity.getOrderNo());
//                    }
//                    if (accountRecordEntity.getBus() == AccountRecordBusEnum.BACK.getIndex()) {
//                        name = "";
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.CASH.getIndex())) {
//                            name = AccountRecordTypeEnum.CASH.getValue();
//                        }
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.COUPON.getIndex())) {
//                            name = AccountRecordTypeEnum.COUPON.getValue();
//                        }
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.VOUCHER.getIndex())) {
//                            name = AccountRecordTypeEnum.VOUCHER.getValue();
//                        }
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.EXP.getIndex())) {
//                            name = AccountRecordTypeEnum.EXP.getValue();
//                        }
//                        if (accountRecordEntity.getType().equals(AccountRecordTypeEnum.POINT.getIndex())) {
//                            name = AccountRecordTypeEnum.POINT.getValue();
//                        }
//                        if (accountRecordEntity.getToUserId().equals(Const.ADMIN_ID)) {
//                            res.add(userDao.get(accountRecordEntity.getToUserId()).getName() + userDao.get(accountRecordEntity.getToUserId()).getCode() + AccountRecordBusEnum.BACK.getValue() + name + accountRecordEntity.getAmount());
//                        } else {
//                            res.add("公司退回" + userDao.get(accountRecordEntity.getToUserId()).getName() + userDao.get(accountRecordEntity.getToUserId()).getCode() + name + accountRecordEntity.getAmount());
//                        }
//                    }
//                    if (accountRecordEntity.getBus().equals(AccountRecordBusEnum.PAYMENT.getIndex())) {
//                        res.add(userEntity.getName() + userEntity.getCode() + "下单,给" + userDao.get(accountRecordEntity.getToUserId()).getName() + AccountRecordBusEnum.PAYMENT.getValue() + accountRecordEntity.getAmount() + "," + Const.ORDER_NO + orderEntity.getOrderNo());
//                    }
//                }
//            }
//
//            //根据订单编号remark获取订单  针对代理有利产品
//            List<MallOrderEntity> mallOrderEntitys = mallOrderDao.findByRemark(orderNo);
//            if (mallOrderEntitys != null) {
//                for (MallOrderEntity mallOrderEntity : mallOrderEntitys) {
//                    //根据订单编号查询账户记录
//                    entities = accountRecordDao.findByInfo(mallOrderEntity.getOrderNo());
//                    String remark = mallOrderEntity.getRemark();
//                    String info = "";
//                    if (remark.contains(Const.ORDER_NO) && mallOrderEntity.getBusType().equals(MallOrderBusTypeEnum.AUTO_BUY.getIndex())) {
//                        info = remark.split(Const.ORDER_NO)[1];
//                    }
//                    if (mallOrderEntity.getBusType().equals(MallOrderBusTypeEnum.RETURN.getIndex())) {
//                        res.add(userDao.get(mallOrderEntity.getUserId()).getName() + MallOrderBusTypeEnum.RETURN.getValue() + "," + Const.ORDER_NO + mallOrderEntity.getOrderNo());
//                        continue;
//                    }
//                    List<AccountRecordEntity> accountRecordEntities = accountRecordDao.findByOrderNoAndBusType(info, AccountRecordBusEnum.PAYMENT.getIndex());
//                    BigDecimal money = BigDecimal.ZERO;
//                    if (accountRecordEntities != null && accountRecordEntities.size() > 0) {
//                        money = accountRecordEntities.get(0).getAmount();
//                    }
//
//                    if (entities != null && entities.size() > 0) {
//                        //获取订单带来连锁奖励
//                        for (AccountRecordEntity accountRecordEntity : entities) {
//
//                            if (null != accountRecordEntity.getInfo() && accountRecordEntity.getInfo().contains(MallOrderBusTypeEnum.AUTO_BUY.getValue())) {
//                                res.add(userDao.get(accountRecordEntity.getFromUserId()).getName() + MallOrderBusTypeEnum.AUTO_BUY.getValue() + accountRecordEntity.getAmount() + ",获得:" + money.subtract(accountRecordEntity.getAmount()) + "," + Const.ORDER_NO + mallOrderEntity.getOrderNo());
//                            }
//                        }
//                    }
//                    //存在 递归调方法
//                    findOrderNo(mallOrderEntity.getOrderNo(), res);
//                }
//            }
//        } else return res;
//        // 不存在返回
//        return res;
//    }

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private AccountDao accountDao;

    /**
     * 查询跟上一级别的经验值之差
     *
     * @param userId
     * @return
     */
    @Override
    public BigDecimal findTopLv(Long userId) {
//        AccountEntity accountEntity = this.accountDao.findByUserIdAndType(userId, AccountTypeEnum.EXP.getIndex());
////        LevelEntity userLevel = this.levelDao.findByUserId(userId);
////        LevelEntity levelEntity = this.levelDao.findTopLv(userLevel.getLv());
////        if (levelEntity == null) {
////            return BigDecimal.ZERO;
////        }
////        if (levelEntity.getType() == LevelTypeEnum.PRI.getIndex()) {
////            return BigDecimal.ZERO;
////        }
////        if (accountEntity != null && accountEntity.getAmount() != null) {
////            return levelEntity.getAmount().subtract(accountEntity.getAmount());
////        }
//        return levelEntity.getAmount();
        return null;
    }


    //自动升级
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoLevel(Long userId) {
        if (userId.equals(Const.ADMIN_ID)) {
            return;
        }
        //当前用户的级别
        UserEntity user = userDao.get(userId);
        LevelEntity level = levelDao.get(user.getLevelId());
        List<UserEntity> users = userDao.findByTop(userId);
        int countVip0 = 0;//准VIP
        int countVip = 0;
        int countV1 = 0;
        int countV2 = 0;
        int countV3 = 0;
        for (UserEntity temUser : users) {
            if (temUser.getLevelId().equals(53L)) {//准VIP
                countVip0++;
            }
            if (temUser.getLevelId().equals(45L)) {//VIP
                countVip++;
            }
            if (temUser.getLevelId().equals(51L)) {//V1 白钻
                countV1++;
            }
            if (temUser.getLevelId().equals(50L)) {//V2 粉钻
                countV2++;
            }
            if (temUser.getLevelId().equals(52L)) {//V3 蓝钻
                countV3++;
            }
        }
//        if (countV3 >= 3) { //三条线 TODO 升级红钻
//            if (level.getLv() > 1) {
//                user.setLevelId(44L);
//                userDao.update(user);
//                autoLevel(user.getPid());
//                return;
//            }
//        }
//        if (countV2 + countV3 >= 3) { //升级蓝钻 三条线 TODO
//            if (level.getLv() > 2) {
//                user.setLevelId(52L);
//                userDao.update(user);
//                autoLevel(user.getPid());
//                return;
//            }
//
//        }

        if (countV1 + countV2 + countV3 >= 3) { //升级粉钻
            if (level.getLv() > 3) {
                user.setLevelId(50L);
                userDao.update(user);
                upLevelF(user.getId());
//                autoLevel(user.getPid());
                return;
            }
        }

//        if (countVip >= 3||countVip0>=3) { //推荐VIP或者准VIP 都可以升级
        if (countVip + countVip0 + countV1 + countV2 + countV3 >= 3) { //升级白钻
            if (level.getLv() > 4) {
                user.setLevelId(51L);
                userDao.update(user);
                autoLevel(user.getPid());
                return;
            }
        }


//       throw new RRException("未达到升级条件!");
    }

    //蓝钻升级 红钻升级
    //三条线粉钻或者蓝钻升级蓝钻  三条线蓝钻升级红钻
    //当有升级 粉钻或者蓝钻
    public void upLevelF(Long userId) {
        //查询系统所有蓝钻数
        List<UserEntity> user1s = userDao.findByLevelId(52L);
        //筛选不是手动的
        user1s = user1s.stream().filter(userEntity -> userEntity.getManLv() != 1).collect(Collectors.toList());
        //查询系统所有粉钻数
        List<UserEntity> user2s = userDao.findByLevelId(50L);
        //总数
        List<UserEntity> users = new ArrayList<>();
        users.addAll(user1s);
        users.addAll(user2s);
        //依次排查升级人的上级是否达到升级条件
        Integer count = 0;
        Long pid = userDao.get(userId).getPid();
        while (!pid.equals(Const.ADMIN_ID)) {
            count++;
            if (count >= 100) {
                throw new RRException("升级循环失败了!");
            }
            UserEntity top = userDao.get(pid);
            //三条线都达到了数量 升级为蓝钻
            if (treeNumber(pid, users, 3)) {
                LevelEntity levelEntity = levelDao.get(top.getLevelId());
                if (levelEntity.getLv() >= 3) { //蓝钻一下 升级蓝钻
                    top.setLevelId(52L);
                    userDao.update(top);
                    //升级蓝钻后出发升级蓝钻反应
                    upLevelL(top.getId());
                }
            }
            //循环
            pid = top.getPid();
        }
    }


    //当有人升级蓝钻
    public void upLevelL(Long userId) {
        //查询系统所有蓝钻数
        List<UserEntity> users = userDao.findByLevelId(52L);
        //筛选不是手动的
        users = users.stream().filter(userEntity -> userEntity.getManLv() != 1).collect(Collectors.toList());
        //查询系统所有粉钻数
        List<UserEntity> user2s = userDao.findByLevelId(50L);
        user2s.addAll(users);
        Integer count = 0;
        Long pid = userDao.get(userId).getPid();
        while (!pid.equals(Const.ADMIN_ID)) {
            count++;
            if (count >= 100) {
                throw new RRException("升级循环失败了!");
            }
            UserEntity top = userDao.get(pid);
            //升级红钻条件 三条线都达到了数量 升级为红钻
            if (treeNumber(pid, users, 3)) {
                LevelEntity levelEntity = levelDao.get(top.getLevelId());
                if (levelEntity.getLv() >= 2) { //红钻以下 升级红钻
                    top.setLevelId(44L);
                    userDao.update(top);
                }
            }
            //升级蓝钻条件
            if (treeNumber(pid, user2s, 3)) {
                LevelEntity levelEntity = levelDao.get(top.getLevelId());
                if (levelEntity.getLv() >= 3) { //蓝钻以下 升级蓝钻
                    top.setLevelId(52L);
                    userDao.update(top);
                    //触发升级蓝钻
                    upLevelL(top.getId());
                    break;
                }
            }
            //循环
            pid = top.getPid();
        }
    }




    private Boolean treeNumber(Long userId, List<UserEntity> users, Integer count) {
        //所有下级
        List<UserEntity> childList = userDao.findByTop(userId);
        List<Long> userIds = childList.stream().map(UserEntity::getId).collect(Collectors.toList());
        //下级计数
        Map<Long, Integer> sum = new HashMap<>();
        for (UserEntity tem : users
        ) {
            Integer temC = 0;
            while (!tem.getId().equals(Const.ADMIN_ID)) {
                temC++;
                if (temC > 100) {
                    throw new RRException("升级死循环!");
                }
                //是一条线 map 排除重复的线
                if (userIds.contains(tem.getId())) {
                    sum.put(tem.getId(), 0);
                    break;
                }
                tem = userDao.get(tem.getPid());
            }
        }
        if (sum.keySet().size() >= count) {
            return true;
        }
        return false;
    }







//    /**
//     * 店铺有利
//     *
//     * @param userId
//     * @param time
//     * @return
//     */
//    private BigDecimal shopReward(Long userId, String time) {
//        return getBigDecimal(userId, time, AccountRecordBusEnum.SHOP.getIndex());
//    }

//    /**
//     * 店铺管理利润
//     *
//     * @param userId
//     * @param time
//     * @return
//     */
//    private BigDecimal shopManageReward(Long userId, String time) {
//        //总收款
//        return getBigDecimal(userId, time, AccountRecordBusEnum.SHOP_MANAGER_REWARD.getIndex());
//    }

    private BigDecimal getBigDecimal(Long userId, String time, Integer bus) {
        //总收款
        BigDecimal shopReward = new BigDecimal(0);
        //追回
        BigDecimal shopBack = new BigDecimal(0);
        //获取该用户的店铺利润or店铺管理利润记录  奖励
        List<AccountRecordEntity> shopEntities = accountRecordDao.findByToUserIdAndBus(userId, bus, time);
        if (shopEntities != null && shopEntities.size() > 0) {
            for (AccountRecordEntity accountRecordEntity : shopEntities) {
                //只计算已经完成的店铺利润
                if (accountRecordEntity.getStatus() == AccountRecordStatusEnum.DONE.getIndex()) {
                    shopReward = shopReward.add(accountRecordEntity.getAmount());
                }
            }
        }
        //追回
        List<AccountRecordEntity> shopEntitiesBack = accountRecordDao.findByFromUserIdAndBus(userId, bus, time);
        if (shopEntitiesBack != null && shopEntitiesBack.size() > 0) {
            for (AccountRecordEntity accountRecordEntity : shopEntitiesBack) {
                //只计算已经完成的店铺利润
                if (accountRecordEntity.getStatus() == AccountRecordStatusEnum.DONE.getIndex()) {
                    shopBack = shopBack.add(accountRecordEntity.getAmount());
                }
            }
        }
        return shopReward.subtract(shopBack);
    }

    //代理有利
//    private BigDecimal agentReward(Long userId, String time) {
//        //待收款
//        List<AccountRecordEntity> accountReward = accountRecordDao.findByToUserIdAndBus(userId, AccountRecordBusEnum.PAYMENT.getIndex(), time);
//        //自动进货款
//        List<AccountRecordEntity> accountBack = accountRecordDao.findByFromUserIdAndBus(userId, AccountRecordBusEnum.AUTO_PAY.getIndex(), time);
//
//        //总收款
//        BigDecimal agentReward = getAgentAmount(accountReward);
//        //自动进货款
//        BigDecimal agentBack = getAgentAmount(accountBack);
//
//        return agentReward.subtract(agentBack);
//    }

    //获取代理有利累积收款和自动进货款
    private BigDecimal getAgentAmount(List<AccountRecordEntity> accountReward) {
        BigDecimal agentReward = new BigDecimal(0);
        if (null != accountReward && accountReward.size() > 0) {
            for (AccountRecordEntity recordEntity : accountReward) {
                if (null != recordEntity.getType() && recordEntity.getType() == AccountRecordTypeEnum.CASH.getIndex() && recordEntity.getStatus() == AccountRecordStatusEnum.DONE.getIndex()) {
                    if (null != recordEntity.getAmount()) {
                        agentReward = agentReward.add(recordEntity.getAmount());
                    }
                }
            }
        }
        return agentReward;
    }

    //换购有利
    private BigDecimal voucherReward(Long userId, List<AccountRecordEntity> accountReward, List<AccountRecordEntity> accountBack) {
        //奖励
        BigDecimal voucherReward = new BigDecimal(0);
        //追回
        BigDecimal voucherBack = new BigDecimal(0);
        //奖励的
        if (null != accountReward && accountReward.size() > 0) {
            for (AccountRecordEntity recordEntity : accountReward) {
                if (null != recordEntity.getType() && recordEntity.getType() == AccountRecordTypeEnum.VOUCHER.getIndex() && recordEntity.getStatus() == AccountRecordStatusEnum.DONE.getIndex()) {
                    if (null != recordEntity.getAmount()) {
                        voucherReward = voucherReward.add(recordEntity.getAmount());
                    }
                }
            }
        }
        //退回的
        if (null != accountBack && accountBack.size() > 0) {
            for (AccountRecordEntity recordEntity : accountBack) {
                if (null != recordEntity.getType() && recordEntity.getType() == AccountRecordTypeEnum.VOUCHER.getIndex() && recordEntity.getStatus() == AccountRecordStatusEnum.DONE.getIndex()) {
                    if (null != recordEntity.getAmount()) {
                        if (recordEntity.getToUserId() == userId) {
                            continue;
                        }
                        voucherBack = voucherBack.add(recordEntity.getAmount());
                    }
                }
            }
        }
        return voucherReward.subtract(voucherBack);
    }

    //分享有利

}
